﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Estore.ViewModels;
using Estore.Models;

namespace Estore.Controllers
{
    public class AccountController : BaseController
    {
        //
        // GET: /Account/
        public EFEstoreRepository repository = new EFEstoreRepository();
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult showlogon()
        {
            return PartialView("LogonUserControl");
        }
        [HttpGet]
        public ActionResult Logon()
        {
            return View();
        }
        
        [HttpPost]
        public ActionResult Logon(LogonModel log)
        {
            int data=-1;
            if (!ModelState.IsValid)
            {
                Session["user_id"] = null;

                return Json(data);
                

            }
            var kt = repository.ValidateUser(log.User_name, log.Pass_word);
            if (kt != null)
            {
                data = 1;
                Session["user_id"] = kt.User_id;
                return Json(data);
            }

            else
            {
                Session["user_id"] = null;
                ModelState.AddModelError("", "The user name or password provided is incorrect.");
                //return View(log);
                return Json(data);
            }

          
          
        }
       

        public ActionResult Logoff()     
        {
            if (Session["user_id"] != null)
                Session["user_id"] = null;
            return RedirectIndex();
        }
        [HttpGet]
        public ActionResult Register()
        {
           
            return View();
        }
        
        [HttpPost]
        public ActionResult Register(RegisterModel user)
        {

            if (!ModelState.IsValid)
            {
                
                return View(user);
                
            }
            var kt = repository.finduserbyloginname(user.User_name);
            if (kt != null)
            {
                ModelState.AddModelError("Login", "Tên dăng nhập bị trùng");
                return View(user);
            }
            var newuser = new User
            {
                User_name = user.User_name,
                Pass_word = user.Pass_word,
                Full_name = user.Full_name,
                Sex = user.Sex,
                Address = user.Address,
                Email = user.Email,
                Phone = user.Phone,
                Avarta = user.Avarta,
                Yahoo = user.Yahoo,
                Type = 2
            };
            repository.addusers(newuser);
            repository.commitchange();
            return RedirectIndex();
        }
    }
}
